package com.common.www.controller.programme;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.SupplyCompanyScheme;
import com.common.www.bean.entity.project.Project;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.programme.ContrastSchemeService;
import com.common.www.service.programme.ProjectSchemeService;
import com.common.www.service.programme.SupplyCompanySchemeService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.BiddingCompanyService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/supplyCompanyScheme"})
@Api(tags = "MGT 方案管理接口")
public class MGTSupplyCompanySchemeController extends DefaultCrudController<SupplyCompanyScheme, Long> {
    @Autowired
    private ContrastSchemeService service;
    @Autowired
    private ProjectSchemeService projectSchemeService;
    @Autowired
    private SupplyCompanySchemeService supplyCompanySchemeService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private BiddingCompanyService biddingCompanyService;

    protected IBaseService getService() {
        return service;
    }

    @ApiOperation("查询上传的供应商方案列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/getSupplyCompanyScheme", method = RequestMethod.POST)
    public Result getSupplyCompanyScheme(Long projectId, Integer jieDuan) {
        if (ParamsUtils.isInputEmpty(projectId, jieDuan)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("project.id",projectId);
        hashMap.put("jieDuan",jieDuan);
        List<SupplyCompanyScheme> supplyCompanySchemeList = supplyCompanySchemeService.queryToList(hashMap,null);

        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, List<SupplyCompanyScheme>> idList = supplyCompanySchemeList.stream().collect(Collectors.groupingBy(SupplyCompanyScheme :: getSupplyCompanyName));
        for (Map.Entry<String, List<SupplyCompanyScheme>> item : idList.entrySet()) {
            List<SupplyCompanyScheme> value = item.getValue();

            Map<String, Object> tempMap = new HashMap<>();
            if (value.size() > 0){
                tempMap.put("project",value.get(0).getProject());
                tempMap.put("supplyCompanyName",value.get(0).getSupplyCompanyName());
                tempMap.put("uploadTime",value.get(0).getCreateTime());
                tempMap.put("jieDuan",jieDuan);
                tempMap.put("fileName",value.get(0).getFileName());
            }
            mapList.add(tempMap);
        }
        return R.ok(mapList);
    }


    @ApiOperation("某个供应商方案详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/getSupplyCompanySchemeDetailList", method = RequestMethod.POST)
    public Result getSupplyCompanySchemeDetailList(Long projectId,String supplyCompanyName, Integer jieDuan) {
        if (ParamsUtils.isInputEmpty(projectId, supplyCompanyName,jieDuan)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("project.id",projectId);
        hashMap.put("supplyCompanyName",supplyCompanyName);
        hashMap.put("jieDuan",jieDuan);
        List<SupplyCompanyScheme> supplyCompanySchemeList = supplyCompanySchemeService.queryToList(hashMap,null);
        return R.ok(supplyCompanySchemeList);
    }


    @ApiOperation("编辑信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        SupplyCompanyScheme contrastScheme = JSON.parseObject(json, SupplyCompanyScheme.class);
        if (contrastScheme.getId() == null) {
            supplyCompanySchemeService.saveAndFlush(contrastScheme);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            SupplyCompanyScheme existingProject = supplyCompanySchemeService.getByIdLogic(contrastScheme.getId());
            if (existingProject != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(contrastScheme, existingProject, "id");
                // 然后保存更新后的对象
                supplyCompanySchemeService.saveAndFlush(existingProject);
            } else {
                // 如果不存在，则保存解析出来的对象
                supplyCompanySchemeService.saveAndFlush(contrastScheme);
            }
        }
        return R.ok(contrastScheme);
    }

    @ApiOperation("按项目的供应商和阶段删除方案")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplyCompanyName", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "jieDuan", value = "", defaultValue = ""),
    })
    @RequestMapping(value = "/conditionDelete", method = RequestMethod.POST)
    public Result conditionDelete(Long projectId,String supplyCompanyName, Integer jieDuan) {
        if (ParamsUtils.isInputEmpty(projectId,supplyCompanyName, jieDuan)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        supplyCompanySchemeService.conditionDelete(projectId,supplyCompanyName, jieDuan);
        return R.ok();
    }

    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            SupplyCompanyScheme scheme = supplyCompanySchemeService.findOne(ids[i]);
            if(scheme!=null){
                scheme.setFlag(0);
                supplyCompanySchemeService.save(scheme);
            }
        }
        return R.ok();
    }


    @ApiOperation(value = "导入供应商方案", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importSupplyCompanyScheme", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importSupplyCompanyScheme(MultipartFile file, Long projectId, Integer jieDuan) throws Exception {
        Project project = projectService.findOne(projectId);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, fileName);
        List<SupplyCompanyScheme> listImport = supplyCompanySchemeService.importSimulate(workbook,project,fileName,jieDuan);
        //Excel表格存在合并项，整理listImport的数据格式后再保存
        List<SupplyCompanyScheme> listArrange = new ArrayList<>();
        String category = null;
        String minorItems = null;
        for (SupplyCompanyScheme scheme : listImport){
            String tempCategory = scheme.getCategory();
            String tempMinorItems = scheme.getMinorItems();
            if (StringUtils.isNotEmpty(tempCategory)){
                category = tempCategory;
            }else {
                if (StringUtils.isNotEmpty(category)){
                    scheme.setCategory(category);
                }
            }
            if (StringUtils.isNotEmpty(tempMinorItems)){
                minorItems = tempMinorItems;
            }else {
                if (StringUtils.isNotEmpty(minorItems)){
                    scheme.setMinorItems(minorItems);
                }
            }
            listArrange.add(scheme);
        }
        // 先删除原来的
        supplyCompanySchemeService.conditionDelete(projectId,listArrange.get(0).getSupplyCompanyName(), jieDuan);
        supplyCompanySchemeService.save(listArrange);
        return R.ok();
    }



}

